import Vue from 'vue'
import VueRouter from 'vue-router'
import permission from '../permission'
import store from '../store'

// import setting from './modules/setting'
import maintenanceImplement from './modules/maintenance-implement'
// import expensePlan from './modules/expense-plan'
// import workspace from './modules/workspace'
// import maintenanceDecision from './modules/maintenance-decision'
// import interiorWork from './modules/interior-work'
// import assetManagement from './modules/asset-management'
// import technicalEvaluation from './modules/technical-evaluation'
// import statisticAnalysis from './modules/statistic-analysis'
// import auxiliaryDecision from './modules/auxiliary-decision'
// import message from './modules/message'

Vue.use(VueRouter)

export const fixedRoutes = []

export const dynamicRoutes = [
    {
        path: '/',
        redirect: '/maintenance-implement',
        name: 'Home'
    },
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/result/404'),
        hidden: true
    },
    // 工作台
    // workspace,
    // // 资产管理
    // assetManagement,
    // // 日常养护
    // maintenanceDecision,
    // // 预算计划
    // expensePlan,
    // 养护工程
    maintenanceImplement
    // // 内业管理
    // interiorWork,
    // // 路况技术评定
    // technicalEvaluation,
    // // 养护辅助决策
    // auxiliaryDecision,
    // // 统计分析
    // statisticAnalysis,
    // // 综合设置
    // setting,
    // // 消息中心
    // message
]

const assignTop = routes => {
    // 只要有title的作为顶部一级菜单
    const top = routes.filter(item => (item.meta || {}).title)
    store.commit('routes/setTop', top)
}

const removePushPromise = () => {
    const raw = VueRouter.prototype.push
    VueRouter.prototype.push = function(location, resolve, reject) {
        return raw
            .call(this, location)
            .then(data => {
                // 在路由push跳转时，获取有权限的路由名，如果跳转路由名称不在权限内，则跳转404
                const routerNames = store.state.routes.routerNames
                if (!routerNames.includes(data.name)) {
                    router.push({ name: '404' })
                }

                resolve && resolve(data)
            })
            .catch(err => {
                if (err) {
                    const isString = Object.prototype.toString.call(err) === '[object String]'
                    if (isString && !err.includes('Avoided redundant')) {
                        reject && reject(err)
                    }
                }
            })
    }
}

const generateMeta = routes => {
    const rs = routes.map(r => {
        if (r.hide) {
            const meta = r.meta || {}
            meta.hide = r.hide
            r.meta = {
                ...meta
            }
        } else {
            if (r.children && r.children.length > 0) {
                let c = r.children
                c = generateMeta(c)
                r.children = c
            }
        }
        return r
    })
    return rs
}

const processRoutes = routes => {
    assignTop(routes)
    routes = generateMeta(routes)
    return routes
}

const createRouter = (routes = fixedRoutes) => {
    const config = {
        // base: process.env.PUBLIC_PUBLIC_PATH,
        mode: 'history',
        routes: processRoutes(routes)
    }
    const router = new VueRouter(config)
    permission(router)
    return router
}

const router = createRouter()
removePushPromise()

// 导航上的消息提醒功能
// 每次路由跳转后都更新一次警告消息数量
// router.afterEach((to, from) => {
//     // 如果是登录页，不作处理
//     if (to.path === '/login') { return }
//     store.dispatch('routes/queryBadge')
// })

const filterRoutes = (routes, permission = []) => {
    const routerNames = []
    const filterMenus = (routes, codes) => {
        return routes.reduce((acc, r) => {
            const meta = r.meta || {}
            const code = meta.code
            // 有权限控制的菜单, 在 meta 中设置 code
            if (code !== undefined) {
                if (codes.has(code)) {
                    const children = r.children || []
                    if (children.length > 0) {
                        r.children = filterMenus(children, codes)
                    }
                    acc.push(r)
                    routerNames.push(r.name)
                }
            } else {
                const children = r.children || []
                if (children.length > 0) {
                    r.children = filterMenus(children, codes)
                }
                acc.push(r)
                routerNames.push(r.name)
            }
            return acc
        }, [])
    }
    // 把有权限的路由名称存入store，用于判断是否有权限
    store.commit('routes/setRouterNames', routerNames)

    const ms = new Map()
    permission.forEach(p => {
        const code = p.code
        ms.set(code, null)
    })

    routes = filterMenus(routes, ms)
    return routes
}

export const resetRoutes = () => {
    const defaultRouter = createRouter()
    router.matcher = defaultRouter.matcher
}

export const processPermission = permissions => {
    const permissionRoutes = filterRoutes(dynamicRoutes, permissions)
    const all = fixedRoutes.concat(permissionRoutes)
    // 路由最后匹配不到时，跳转404
    all.push({ path: '*', redirect: '/404', hidden: true })
    const permissionRouter = createRouter(all)
    router.matcher = permissionRouter.matcher
}

export default router
